import React from 'react';
import { Radio, Checkbox, InputNumber, Modal, Spin, Button } from 'antd';
const RadioGroup = Radio.Group;
const RadioButton = Radio.Button;
import * as actions from './../../actions/frontEnd/homeAction';

export default class shoppingCart extends React.Component {
    constructor(props) {
      super(props);
      this.state = {
        productDetial: null,
        rawData: [],
        shoppingCartList: [],
        loading: false,
        cartIsEmpty: true,

        indeterminate: false,
        checkedAll: false,

        colorSizes: false,
        updateLoading: false,
        selectSizes: "",
        selectColors: "",
        selectItem: null
      };
    }
    componentDidMount(){
        this.findShoppingCartList();
    }
    findShoppingCartList(){
        actions.findShoppingCartListByType(this, {pageNumber: 1, pageSize: 1000});
    }
    onSelectSizes(val){
      this.setState({selectSizes: val.target.value});
    }
    onSelectColors(val){
      this.setState({selectColors: val.target.value});
    }
    btnShowColorAndSize(val, item){
      var that = this;
      if(val == true){
        actions.findProductDetial(this, item.pId);

        this.setState({colorSizes: val}, function(){
          setTimeout(function(){
            that.setState({selectItem: item, selectSizes: item.size, selectColors: item.productColor});
          }, 400);
        });
      }else {
        this.setState({colorSizes: val});
      }
    }
    btnColorAndSize(){
      this.state.selectItem.size = this.state.selectSizes;
      this.state.selectItem.productColor = this.state.selectColors;
      this.setState({updateLoading: true});
      actions.addOrEditShoppingCartByEdit(this, this.state.selectItem, "");
    }
    checkAll(val){
      for (var i = 0; i < this.state.shoppingCartList.length; i++) {
          this.state.shoppingCartList[i].isCheck = val.target.checked;
          this.state.shoppingCartList[i].typeIndeterminate = false;
          for (var j = 0; j < this.state.shoppingCartList[i].items.length; j++) {
              this.state.shoppingCartList[i].items[j].isCheck = val.target.checked;
          }
      }
      this.setState({shoppingCartList: this.state.shoppingCartList, checkedAll: val.target.checked, indeterminate: false});
    }
    selectThisType(item, val){
      for (var i = 0; i < this.state.shoppingCartList.length; i++) {
        if(item.type == this.state.shoppingCartList[i].type){
          this.state.shoppingCartList[i].isCheck = val.target.checked;
          this.state.shoppingCartList[i].typeIndeterminate = false;
          for (var j = 0; j < this.state.shoppingCartList[i].items.length; j++) {
              this.state.shoppingCartList[i].items[j].isCheck = val.target.checked;
          }
        }
      }

      var isNoItem = false; var isSelectAll = false; var indexCount = 0;
      for (var i = 0; i < this.state.shoppingCartList.length; i++) {
        if(this.state.shoppingCartList[i].isCheck == true){
          isNoItem = true; indexCount++;
        }
        if(this.state.shoppingCartList.length == indexCount){
          isSelectAll = true;
        }
      }

      if(isNoItem == false){
        //一个都没有
        this.setState({
          checkedAll: false,
          indeterminate: false
        });
      }else {
        if(isNoItem == true && isSelectAll == true){
          //全选
          this.setState({
            checkedAll: true,
            indeterminate: false
          });
        }else {
          //至少有一个
          this.setState({
            checkedAll: false,
            indeterminate: true
          });
        }
      }
      this.setState({shoppingCartList: this.state.shoppingCartList});
    }
    selectByThis(subItem, val){
      for (var i = 0; i < this.state.shoppingCartList.length; i++) {
        if(this.state.shoppingCartList[i].type == subItem.type){
          for (var j = 0; j < this.state.shoppingCartList[i].items.length; j++) {
            if (this.state.shoppingCartList[i].items[j].id == subItem.id){
              this.state.shoppingCartList[i].items[j].isCheck = val.target.checked;
              break;
            }
          }
          break;
        }
      }
      var isNoItem = false; var isSelectAll = false; var indexCount = 0; var tempItem = null;
      for (var i = 0; i < this.state.shoppingCartList.length; i++) {
        if(this.state.shoppingCartList[i].type == subItem.type){
          tempItem = this.state.shoppingCartList[i];
          for (var j = 0; j < this.state.shoppingCartList[i].items.length; j++) {
            if(this.state.shoppingCartList[i].items[j].isCheck == true){
              isNoItem = true; indexCount += 1;
            }
          }
          if(this.state.shoppingCartList[i].items.length == indexCount){
            isSelectAll = true;
          }
        }
      }

      if(isNoItem == false){
        //一个都没有
        tempItem.isCheck = false;
        tempItem.typeIndeterminate = false;
      }else {
        if(isNoItem == true && isSelectAll == true){
          //全选
          tempItem.isCheck = true;
          tempItem.typeIndeterminate = false;
        }else {
          //至少有一个
          tempItem.isCheck = false;
          tempItem.typeIndeterminate = true;
        }
      }
      //----------------------------判断全选与否---------------------
      var isNoItem = false; var isSelectAll = false; var indexCount = 0;
      for (var i = 0; i < this.state.shoppingCartList.length; i++) {
        if(this.state.shoppingCartList[i].isCheck == true){
          isNoItem = true; indexCount++;
        }
        if(this.state.shoppingCartList.length == indexCount){
          isSelectAll = true;
        }
      }

      if(isNoItem == false){
        //一个都没有
        this.setState({
          shoppingCartList: this.state.shoppingCartList,
          checkedAll: false,
          indeterminate: false
        });
      }else {
        if(isNoItem == true && isSelectAll == true){
          //全选
          this.setState({
            shoppingCartList: this.state.shoppingCartList,
            checkedAll: true,
            indeterminate: false
          });
        }else {
          //至少有一个
          this.setState({
            shoppingCartList: this.state.shoppingCartList,
            checkedAll: false,
            indeterminate: true
          });
        }
      }
    }
    deleteByOne(scId){
       var that = this;
       Modal.confirm({
        title: '提示：',
        content: '你确定要 删除 此商品吗？',
        onOk() {
          var scIds = new Array(scId);
          actions.removeShoppingCart(that, scIds);
        }
      });
    }
    clearSelectProduct(){
      var that = this;
      Modal.confirm({
       title: '提示：',
       content: '你确定要 删除 所有商品吗？',
       onOk() {
         var scIds = new Array();
         for (var i = 0; i < that.state.rawData.length; i++) {
           scIds.push(that.state.rawData[i].id);
         }
         actions.removeShoppingCart(that, scIds);
       }
      });
    }
    setPurchaseNum(item, num){
      item.purchaseNum = num;
      // delete item.isCheck;
      actions.addOrEditShoppingCartByEdit(this, item, "num");
    }
    render() {
      var tableElement = null; var totalAllAmount = 0; var totalNum = 0;

      if(this.state.shoppingCartList.length <= 0){
        tableElement = <div className="divEmptData">对不起，当前购物车为空。</div>
      }else {
        tableElement = <div>
        {
          this.state.shoppingCartList.map((item, index) => {
              var totalAmount = 0;
              var tbody = <tbody>
              {
                item.items.map((subItem, subIndex) => {
                    if(subItem.isCheck == true){
                      totalAmount += subItem.discountPrice*subItem.purchaseNum;
                      totalAmount = parseFloat(totalAmount.toFixed(2));

                      totalNum += subItem.purchaseNum;
                      
                      totalAllAmount += subItem.discountPrice*subItem.purchaseNum;
                      totalAllAmount = parseFloat(totalAllAmount.toFixed(2));
                    }
                    return (<tr className="cart_item" key={subIndex}>
                      <td className="top">
                        <div className="cart_item_desc clearfix">
                          <Checkbox className="cart_item_selector" checked={subItem.isCheck} onChange={this.selectByThis.bind(this, subItem)}></Checkbox>
                          <div className="cart_item_desc_wrapper">
                            <a className="cart_item_pic" href="http://cd.jumei.com/i/deal/df1805176968765p3652044.html" target="_blank">
                              <img src={"http://tinsley.oss-cn-shenzhen.aliyuncs.com/" + subItem.productPic}/>
                            </a>
                            <a className="cart_item_link" title={subItem.productName + "(" + subItem.brandName + ")"} href="http://cd.jumei.com/i/deal/df1805176968765p3652044.html" target="_blank">{subItem.productName + "(" + subItem.brandName + ")"}</a>
                            <div className="sku_info">
                              颜色：<span className="cart_item_attribute">{subItem.productColor}</span>&nbsp;   尺寸：<span className="cart_item_capacity">{subItem.size}</span>
                              <a href="javascript:void(0)" style={{marginLeft: '10px'}} onClick={this.btnShowColorAndSize.bind(this, true, subItem)}>颜色、尺寸</a>
                            </div>
                            <div className="sale_info clearfix">  </div>
                          </div>
                        </div>
                      </td>
                      <td>
                        <div className="cart_item_price">
                          <div className="jumei_price">{subItem.discountPrice.toFixed(2)}</div>
                          <div className="market_price ">{subItem.price.toFixed(2)}</div>
                        </div>
                      </td>
                      <td>
                        <InputNumber min={1} defaultValue={subItem.purchaseNum} onChange={this.setPurchaseNum.bind(this, subItem)} />
                      </td>
                      <td>
                        <div className="cart_item_total">
                          <div className="item_total_price">{(subItem.discountPrice*subItem.purchaseNum).toFixed(2)}</div>  <div>省 <span className="item_saved_price">{((subItem.price*subItem.purchaseNum)-(subItem.discountPrice*subItem.purchaseNum)).toFixed(2)}</span></div>
                        </div>
                      </td>
                      <td>
                        <div className="cart_item_option">
                          <a className="icon_small delete_item png" onClick={this.deleteByOne.bind(this, subItem.id)}>删除</a>
                        </div>
                      </td>
                    </tr>)
                })
              }
              </tbody>

              return(
                <table className="cart_group_item cart_group_item_media" key={index}>
                  <thead>
                    <tr>
                      <th className="cart_overview">
                        <div className="cart_group_header">
                          <Checkbox onClick={this.selectThisType.bind(this, item)} checked={item.isCheck} indeterminate={item.typeIndeterminate}>{item.typeText}</Checkbox>
                        </div>
                      </th>
                      <th className="cart_price">聚美价（元）</th>
                      <th className="cart_num">数量</th>
                      <th className="cart_total">小计（元）</th>
                      <th className="cart_option">操作</th>
                    </tr>
                  </thead>
                  {tbody}
                  <tfoot>
                    <tr>
                      <td colSpan="5"> 商品金额： <span className="group_total_price">Rm{totalAmount}</span></td>
                    </tr>
                  </tfoot>
                </table>
              )
          })
        }
        </div>
      }

      var sizes = null; var productColors = null;
      if(this.state.productDetial != null){
        sizes = <RadioGroup value={this.state.selectSizes} onChange={this.onSelectSizes.bind(this)}>
          {
            this.state.productDetial.product.sizes.map((item, index)=>{
              return (<RadioButton key={index} value={item}>{item}</RadioButton>)
            })
          }
        </RadioGroup>

        productColors = <RadioGroup value={this.state.selectColors} onChange={this.onSelectColors.bind(this)}>
          {
            this.state.productDetial.product.productColors.map((item, index)=>{
              return (<RadioButton key={index} value={item}>{item}</RadioButton>)
            })
          }
        </RadioGroup>
      }

      return (
        <div style={{width: '1070px', marginLeft: 'auto', marginRight: 'auto'}}>
            {tableElement}
            <div className="common_handler">
              <div className="right_handler"> 共 <span className="total_amount"> {totalNum} </span> &nbsp;件商品 &nbsp;&nbsp; 商品应付总额：<span className="total_price">Rm{totalAllAmount}</span>
                <a id="go_to_order" className="btn" href="javascript:void(0);">去结算</a>
              </div>
              <label className="cart_all_selector_wrapper">
                <Checkbox className="cart_item_selector" onClick={this.checkAll.bind(this)} checked={this.state.checkedAll} indeterminate={this.state.indeterminate}>全选</Checkbox>
              </label>
              <a className="go_back_shopping" href="/index">继续购物</a>
              <span className="seperate_line">|</span>
              <a className="clear_cart_all" href="javascript:void(0)" onClick={this.clearSelectProduct.bind(this)}>清空选中商品</a>
            </div>
            <Modal
                title="颜色 和 尺寸"
                visible={this.state.colorSizes}
                wrapClassName="center-modal"
                footer={null}
                onCancel={this.btnShowColorAndSize.bind(this, false, null)}
                width="500px"
                maskClosable={false}
                destroyOnClose={true}
            >
                <Spin spinning={this.state.updateLoading} wrapperClassName="spinUpdateLoading" tip="提交中...">
                  <div style={{textAlign: 'left'}}>
                    <div style={{marginBottom: '6px'}}>尺寸:</div>
                    {sizes}
                  </div>
                  <div style={{textAlign: 'left', marginTop: '12px', marginBottom: '15px'}}>
                    <div style={{marginBottom: '6px'}}>产品颜色:</div>
                    {productColors}
                  </div>
                  <div style={{marginTop: '10px'}}>
                      <Button icon="check-circle-o" type="primary" style={{marginRight: '15px'}} onClick={this.btnColorAndSize.bind(this)}>确定修改</Button>
                      <Button icon="close" onClick={this.btnShowColorAndSize.bind(this, false, null)}>取 消</Button>
                  </div>
                </Spin>
            </Modal>
        </div>
      )
    }
}
